package com.ants.boot.core.aspect;

import com.ants.boot.core.annotation.Log;
import com.ants.boot.core.security.user.LoginUser;
import com.ants.boot.system.domain.OperateLog;
import com.ants.boot.system.service.OperateLogService;
import com.ants.boot.utils.IpUtils;
import com.ants.boot.utils.ThreadPoolUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 蚂蚁会花呗
 * @date 2022/1/11 17:11
 */
@Aspect
@Component
public class LogOperateAspect {

    //日志
    Logger logger = LoggerFactory.getLogger(LogOperateAspect.class);

    //时间线程
    private static final ThreadLocal<Date> beginTimeThreadLocal = new NamedThreadLocal<Date>("ThreadLocal beginTime");

    @Autowired
    private OperateLogService operateLogService;

    @Autowired(required = false)
    private HttpServletRequest request;




    @Pointcut("@annotation(com.ants.boot.core.annotation.Log)")
    public void pointcut() {

    }

    /**
     * 前置通知 (在方法执行之前返回)用于拦截Controller层记录用户的操作的开始时间
     *
     * @param joinPoint 切点
     */
    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint) {
        //线程绑定变量（该数据只有当前请求的线程可见）
        Date beginTime = new Date();
        beginTimeThreadLocal.set(beginTime);
    }

    /**
     * 后置通知(在方法执行之后并返回数据) 用于拦截Controller层无异常的操作
     *
     * @param joinPoint 切点
     */
    @AfterReturning("pointcut()")
    public void after(JoinPoint joinPoint) {
        try{
            OperateLog log = new OperateLog();

            //日志描述、操作说明等
            log.setModule(getMethodInfo(joinPoint).get("module").toString());
            log.setOperate(getMethodInfo(joinPoint).get("operate").toString());

            //请求开始时间
            long beginTime = beginTimeThreadLocal.get().getTime();
            long endTime = System.currentTimeMillis();
            //请求耗时
            long time = (endTime-beginTime)/1000;
            log.setCostTime(new BigDecimal(time).setScale(2,BigDecimal.ROUND_HALF_UP));
            log.setCreateTime(LocalDateTime.now());
            log.setStartTime(LocalDateTime.ofEpochSecond(beginTime/1000, 0, ZoneOffset.ofHours(8)));
            log.setEndTime(LocalDateTime.ofEpochSecond(endTime/1000, 0, ZoneOffset.ofHours(8)));
            log.setCostMilliSecond(endTime-beginTime);
            log.setIp(IpUtils.getIpAddress(request));
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            LoginUser loginUser = (LoginUser)authentication.getPrincipal();
            log.setOperatePerson(loginUser.getUsername());
            //线程池存储日志
            ThreadPoolUtils.getPool().execute(new SaveOperateLogThread(log, operateLogService));
        }catch (Exception e){
            logger.error("AOP后置通知异常" + e.getMessage());
        }
    }

    /**
     * 保存日志至数据库
     */
    private static class SaveOperateLogThread implements Runnable {
        private OperateLog operateLog;
        private OperateLogService operateLogService;
        public SaveOperateLogThread(OperateLog operateLog, OperateLogService operateLogService) {
            this.operateLog = operateLog;
            this.operateLogService = operateLogService;
        }
        @Override
        public void run() {
            operateLogService.save(operateLog);
        }
    }

    /**
     * 获取日志注解的操作说明
     * @param joinPoint
     * @return
     * @throws ClassNotFoundException
     */
    private Map<String, Object> getMethodInfo(JoinPoint joinPoint) throws ClassNotFoundException {
        Map<String, Object> map = new HashMap<String, Object>(16);
        //获取目标类名、方法名、相关参数
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        //生成类对象
        Class targetClass = Class.forName(targetName);
        //获取该类中的方法
        Method[] methods = targetClass.getMethods();
        String module = "";
        String operate = "";
        for (Method method : methods) {
            if (!method.getName().equals(methodName)) {
                continue;
            }
            Class[] clazzs = method.getParameterTypes();
            if (clazzs.length != arguments.length) {
                continue;
            }
            module = method.getAnnotation(Log.class).module();
            operate = method.getAnnotation(Log.class).operate();
            map.put("module", module);
            map.put("operate", operate);
        }
        return map;
    }

}
